<!-- 宠物模板管理页面 -->
<template>
	<view class="pet-template-container">
		<!-- 顶部标题 -->
		<view class="header">
			<text class="title">宠物形象管理</text>
		</view>
		
		<!-- 表单区域 -->
		<view class="form-section">
			<view class="form-item">
				<text class="label">宠物类型</text>
				<view class="type-selector">
					<view class="type-option" 
						:class="{'selected': formData.category === '猫'}"
						@tap="selectCategory('猫')">
						<text>猫咪</text>
					</view>
					<view class="type-option"
						:class="{'selected': formData.category === '狗'}"
						@tap="selectCategory('狗')">
						<text>狗狗</text>
					</view>
				</view>
			</view>
			
			<view class="form-item">
				<text class="label">品种名称</text>
				<input class="input" v-model="formData.species" placeholder="请输入宠物品种" />
			</view>
			
			<view class="form-item">
				<text class="label">形象图片</text>
				<view class="image-upload">
					<view class="image-preview" v-if="formData.imageUrl">
						<image :src="formData.imageUrl" mode="aspectFit"></image>
						<view class="delete-image" @tap="deleteImage">×</view>
					</view>
					<view class="upload-btn" @tap="chooseImage" v-else>
						<text class="upload-icon">+</text>
						<text>上传图片</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="button-group">
			<button class="submit-btn" @tap="submitForm" :disabled="!canSubmit">{{submitButtonText}}</button>
		</view>
		
		<!-- 模板列表 -->
		<view class="template-list">
			<view class="list-header">
				<text class="list-title">已添加的形象</text>
			</view>
			<view class="template-item" v-for="item in templates" :key="item.objectId">
				<image class="template-image" :src="item.imageUrl" mode="aspectFit"></image>
				<view class="template-info">
					<text class="template-species">{{item.species}}</text>
					<text class="template-category">{{item.category}}</text>
				</view>
				<view class="template-actions">
					<button class="edit-btn" @tap="editTemplate(item)">编辑</button>
					<button class="delete-btn" @tap="deleteTemplate(item)">删除</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			formData: {
				species: '',
				category: '猫',
				imageUrl: ''
			},
			templates: [],
			isEditing: false,
			editingId: null
		}
	},
	
	computed: {
		canSubmit() {
			return this.formData.category && 
				this.formData.species && 
				this.formData.imageUrl;
		},
		submitButtonText() {
			return this.isEditing ? '保存修改' : '保存模板';
		}
	},
	
	onLoad() {
		// 开发阶段暂时关闭管理员权限检查
		// this.checkAdminAuth()
		this.loadTemplates()
	},
	
	methods: {
		// 检查管理员权限
		async checkAdminAuth() {
			// 开发阶段暂时关闭管理员权限检查
			return true
			
			try {
				const user = await this.$leanCloud.user.getCurrent()
				if (!user || !user.isAdmin) {
					uni.showToast({
						title: '无管理员权限',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			} catch (error) {
				console.error('权限检查失败：', error)
				uni.navigateBack()
			}
		},
		
		// 加载模板列表
		async loadTemplates() {
			try {
				const result = await this.$leanCloud.query('PetTemplate')
				this.templates = result.results || []
			} catch (error) {
				console.error('加载模板失败：', error)
				// 如果是404错误，说明类不存在，这是正常的
				this.templates = []
			}
		},
		
		// 选择类型
		selectCategory(category) {
			this.formData.category = category
		},
		
		// 选择图片
		async chooseImage() {
			try {
				// 使用Promise风格调用uni.chooseImage
				const chooseImagePromise = () => {
					return new Promise((resolve, reject) => {
						uni.chooseImage({
							count: 1,
							sizeType: ['compressed'],
							sourceType: ['album'],
							success: resolve,
							fail: reject
						})
					})
				}
				
				const res = await chooseImagePromise()
				
				if (res && res.tempFilePaths && res.tempFilePaths.length > 0) {
					const tempFilePath = res.tempFilePaths[0]
					const fileName = `template_${Date.now()}.jpg`
					
					uni.showLoading({
						title: '上传中...'
					})
					
					// 使用项目中定义的文件上传API
					const fileData = await this.$leanCloud.file.upload(tempFilePath, fileName)
					
					// 获取文件URL
					this.formData.imageUrl = fileData.url
					
					uni.hideLoading()
				}
			} catch (error) {
				console.error('上传图片失败：', error)
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				})
			}
		},
		
		// 删除图片
		deleteImage() {
			this.formData.imageUrl = ''
		},
		
		// 编辑模板
		editTemplate(template) {
			this.isEditing = true;
			this.editingId = template.objectId;
			this.formData = {
				species: template.species,
				category: template.category,
				imageUrl: template.imageUrl
			};
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			});
		},
		
		// 提交表单
		async submitForm() {
			if (!this.canSubmit) return;
			
			try {
				uni.showLoading({
					title: '保存中...'
				});
				
				if (this.isEditing) {
					// 更新已有模板
					await this.$leanCloud.update('PetTemplate', this.editingId, this.formData);
					uni.showToast({
						title: '更新成功',
						icon: 'success'
					});
				} else {
					// 创建新模板
					await this.$leanCloud.create('PetTemplate', this.formData);
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
				}
				
				// 重置表单
				this.resetForm();
				
				// 重新加载列表
				await this.loadTemplates();
			} catch (error) {
				console.error(this.isEditing ? '更新失败：' : '添加失败：', error);
				uni.showToast({
					title: this.isEditing ? '更新失败' : '添加失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},
		
		// 重置表单
		resetForm() {
			this.formData = {
				species: '',
				category: '猫',
				imageUrl: ''
			};
			this.isEditing = false;
			this.editingId = null;
		},
		
		// 删除模板
		async deleteTemplate(template) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个宠物形象吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({
								title: '删除中...'
							})
							
							// 使用项目中定义的对象删除API
							await this.$leanCloud.delete('PetTemplate', template.objectId)
							
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
							
							// 重新加载列表
							await this.loadTemplates()
						} catch (error) {
							console.error('删除失败：', error)
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							})
						} finally {
							uni.hideLoading()
						}
					}
				}
			})
		}
	}
}
</script>

<style lang="scss">
.pet-template-container {
	min-height: 100vh;
	background-color: #F5F6FA;
	padding: 30rpx;
	
	.header {
		margin-bottom: 30rpx;
		
		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.form-section {
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		
		.form-item {
			margin-bottom: 30rpx;
			
			.label {
				display: block;
				font-size: 28rpx;
				color: #333;
				margin-bottom: 16rpx;
			}
			
			.type-selector {
				display: flex;
				gap: 20rpx;
				
				.type-option {
					flex: 1;
					height: 80rpx;
					background: #f8f8f8;
					border-radius: 12rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 28rpx;
					color: #666;
					
					&.selected {
						background: rgba(139, 92, 255, 0.1);
						border: 2rpx solid #8B5CFF;
						color: #8B5CFF;
					}
				}
			}
			
			.input {
				width: 100%;
				height: 80rpx;
				background: #f8f8f8;
				border-radius: 12rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
			}
			
			.image-upload {
				.image-preview {
					width: 200rpx;
					height: 200rpx;
					position: relative;
					
					image {
						width: 100%;
						height: 100%;
						border-radius: 12rpx;
					}
					
					.delete-image {
						position: absolute;
						top: -20rpx;
						right: -20rpx;
						width: 40rpx;
						height: 40rpx;
						background: rgba(0, 0, 0, 0.5);
						color: #fff;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
				
				.upload-btn {
					width: 200rpx;
					height: 200rpx;
					background: #f8f8f8;
					border-radius: 12rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					
					.upload-icon {
						font-size: 48rpx;
						color: #999;
						margin-bottom: 10rpx;
					}
					
					text {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}
	}
	
	.button-group {
		margin-bottom: 30rpx;
		
		.submit-btn {
			width: 100%;
			height: 90rpx;
			background: #8B5CFF;
			color: #fff;
			border-radius: 45rpx;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			&[disabled] {
				background: #ccc;
			}
		}
	}
	
	.template-list {
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		
		.list-header {
			margin-bottom: 30rpx;
			
			.list-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}
		
		.template-item {
			display: flex;
			align-items: center;
			padding: 20rpx;
			border-bottom: 2rpx solid #f0f0f0;
			
			&:last-child {
				border-bottom: none;
			}
			
			.template-image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				margin-right: 20rpx;
			}
			
			.template-info {
				flex: 1;
				
				.template-species {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 8rpx;
				}
				
				.template-category {
					font-size: 24rpx;
					color: #999;
				}
			}
			
			.template-actions {
				display: flex;
				gap: 10rpx;
				
				.edit-btn,
				.delete-btn {
					font-size: 24rpx;
					padding: 10rpx 20rpx;
					border-radius: 6rpx;
					margin: 0;
				}
				
				.edit-btn {
					background: #8B5CFF;
					color: #fff;
				}
				
				.delete-btn {
					background: #ff4d4f;
					color: #fff;
				}
			}
		}
	}
}
</style> 